package com.ftdigital.primemovers_operators.util.view;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by Curry on 2016-1-17.
 */
public class DrawingBoard extends SurfaceView implements SurfaceHolder.Callback, Runnable{

    Canvas canvas;
    SurfaceHolder surfaceHolder;
    boolean isDrawing;

    Path path;
    Paint paint;
    public DrawingBoard(Context context) {
        super(context);
        init();
    }

    public DrawingBoard(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        setFocusable(true);
        setFocusableInTouchMode(true);
        setKeepScreenOn(true);
        path = new Path();
        paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(20);
        paint.setStyle(Paint.Style.STROKE);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        isDrawing = true;
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        isDrawing = false;
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                path.moveTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                path.lineTo(event.getX(), event.getY());
                break;
        }
        return true;
    }
    @Override
    public void run() {
        long start = System.currentTimeMillis();
        while (isDrawing){
            draw();
        }
        long end = System.currentTimeMillis();
        if ( end  - start < 100)
            try {
                Thread.sleep(100 -(end - start));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }

    private void draw() {
        if (canvas == null)
            return;
        try {
            canvas = surfaceHolder.lockCanvas();
            canvas.drawColor(Color.WHITE);
            canvas.drawPath(path, paint);
        }finally {
                surfaceHolder.unlockCanvasAndPost(canvas);
        }
    }
}
